package net.yuanmomo.socket.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by Hongbin.Yuan on 2016-07-03 14:25.
 */


class TimeServerHandlerBIO implements Runnable {
    private Socket socket;

    public TimeServerHandlerBIO(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        BufferedReader reader = null;
        PrintWriter printWriter = null;
        try {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printWriter = new PrintWriter(this.socket.getOutputStream(), true);

            String currenTime = null;
            String body = null;
            // 不停的等待客户端传输数据,知道不再发送数据为止
            //  EXCHANGE_TIME, POINT, TYPE, AMOUNT,CHECK_STATUS

            while (true) {
                body = reader.readLine();
                if (body == null ) {
                    continue;
                }
                if("c" .equalsIgnoreCase(body)){
                    break;
                }
                System.out.println(String.format("server receive time query"));
                currenTime = "time".equalsIgnoreCase(body) ? System.currentTimeMillis() + "" : "BAD REQUEST";
                printWriter.println(currenTime);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (printWriter != null) {
                printWriter.close();
            }
            if(this.socket != null){
                try {
                    this.socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


